import nmap
import optparse
from datetime import datetime

def nmapScan(tgtHost,tgtPort):
    f = open('../data/dic/Nmap.txt', 'a')
    vul=tgtHost.find('-')
    if vul==-1:
        nmScan = nmap.PortScanner()
        nmReuslt=nmScan.scan(tgtHost,tgtPort)
        l=nmReuslt
        if len(list(l.get('scan')))!=0:
            protocols=nmScan[tgtHost].all_protocols() #返回协议
            for i in range(len(protocols)):
                port=list(nmScan[tgtHost][protocols[i]].keys()) #只返还端口
                for j in range(len(port)):
                    state=nmScan[tgtHost][protocols[i]][port[j]]['state']
                    name=nmScan[tgtHost][protocols[i]][port[j]]['name']
                    product=nmScan[tgtHost][protocols[i]][port[j]]['product']
                    version=nmScan[tgtHost][protocols[i]][port[j]]['version']
                    now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    if state=="open":
                        f.write("[*"+now_time+"] " + tgtHost + " "+protocols[i]+" "+str(port[j]) +" "+state+" "+name+" "+product+" "+version+ "\n")
                        print ("[*"+now_time+"] "+ tgtHost + " "+protocols[i]+" "+str(port[j]) +" "+state+" "+name+" "+product+" "+version)
    else:
        hostlen=len(tgtHost)
        s=""
        sh=tgtHost
        sh=sh.rsplit('.', 1)[0]
        for v in tgtHost[0:vul]:
            s=s+v
            if v==".":
                s=""
        s=int(s)
        ss=int(tgtHost[vul+1:hostlen])
        vuls=ss-s
        for a in range(0,vuls+1):
            s1=s+a
            sh1=sh
            sh1=sh1+"."+str(s1)
            tgtHost=sh1
            nmScan = nmap.PortScanner()
            nmReuslt=nmScan.scan(tgtHost,tgtPort)
            l=nmReuslt
            if len(list(l.get('scan')))!=0:
                protocols=nmScan[tgtHost].all_protocols() #返回协议
                for i in range(len(protocols)):
                    port=list(nmScan[tgtHost][protocols[i]].keys()) #只返还端口
                    for j in range(len(port)):
                        state=nmScan[tgtHost][protocols[i]][port[j]]['state']
                        name=nmScan[tgtHost][protocols[i]][port[j]]['name']
                        product=nmScan[tgtHost][protocols[i]][port[j]]['product']
                        version=nmScan[tgtHost][protocols[i]][port[j]]['version']
                        now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                        if state=="open":
                            f.write("[*"+now_time+"] " + tgtHost + " "+protocols[i]+" "+str(port[j]) +" "+state+" "+name+" "+product+" "+version+ "\n")
                            print ("[*"+now_time+"] "+ tgtHost + " "+protocols[i]+" "+str(port[j]) +" "+state+" "+name+" "+product+" "+version)
    # print(nmReuslt)
    f.close()
def main():
    parser = optparse.OptionParser('usage %prog '+\
                                   '-H <target host> -p <target port>')
    parser.add_option('-H', dest='tgtHost', type='string',\
                      help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='string',\
                      help='specify target port[s] separated by comma')
    
    (options, args) = parser.parse_args()
    
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPort).split(',')
    
    if (tgtHost == None) | (tgtPorts[0] == None):
        # print parser.usage
        print(parser.usage)
        exit(0)
 
    for tgtPort in tgtPorts:
        nmapScan(tgtHost, tgtPort)
 
 
if __name__ == '__main__':
    main()
